<template>
	<el-card class="layout-query">
		<el-form :inline="true" label-width="100px">
			<el-form-item label="关键词" prop="keyword">
				<el-input v-model="state.keyword" placeholder="请输入">
					<template #prepend>
						<el-select v-model="state.keyType" placeholder="请选择" style="width: 100px; min-width: 100px">
							<el-option label="项目编号" value="1" />
							<el-option label="项目名称" value="2" />
							<el-option label="项目负责人" value="3" />
							<el-option label="项目联系人" value="4" />
							<el-option label="承担单位" value="5" />
						</el-select>
					</template>
				</el-input>
			</el-form-item>

			<el-form-item prop="job_status" label="申报年份">
				<el-date-picker
					v-model="datatimelist"
					type="yearrange"
					range-separator="至"
					start-placeholder="开始日期"
					value-format="YYYY"
					end-placeholder="结束日期"
					@change="handleDateChange"
				/>
			</el-form-item>

			<el-form-item prop="dept_id" label="申报阶段">
				<el-select v-model="state.queryForm.processStage" placeholder="请选择" style="width: 100%">
					<el-option v-for="item in progressStatelist" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item prop="job_status" label="申报状态">
				<el-select v-model="state.queryForm.processStatus" placeholder="请选择" style="width: 100%">
					<el-option v-for="item in processStatuslist" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item prop="zy" label="申报结果">
				<el-select v-model="state.queryForm.approvalReview" placeholder="请选择" style="width: 100%">
					<el-option v-for="item in approvalReviewlist" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item>
				<el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>

	<el-card>
		<el-form :inline="true" style="text-align: right">
			<!-- <el-form-item>
				<ma-icon icon="icon-reload"></ma-icon> :disabled="!hasPermission"
			</el-form-item> -->
			<el-form-item v-auth="'M005_Submit'">
				<el-button type="primary" :disabled="!hasPermission" @click="submitHandle">提交</el-button>
			</el-form-item>
			<el-form-item v-auth="'M005_FileUpload'">
				<el-button type="primary" :disabled="!hasPermission2" @click="submitfileHandle">意见及文件上传</el-button>
			</el-form-item>

			<el-form-item v-auth="'M005_SummaryTable'">
				<el-button type="primary" @click="exportHandle">项目汇总表</el-button>
			</el-form-item>
			<el-form-item v-auth="'M005_CancelApprovalFIle'">
				<el-button type="primary" :disabled="!hasPermissionfb" @click="cancelApprovalFIleHandle">取消发布</el-button>
			</el-form-item>
			<!-- <el-form-item>
				<el-button v-auth="'M005_S_CancelPublish'" type="primary" @click="cancleReleaseHandle">取消发布</el-button>
			</el-form-item> -->
			<el-form-item v-auth="'M005_RePublish'">
				<el-button type="primary" :disabled="!hasPermissionqxfb" @click="reissueHandle">重新发布</el-button>
			</el-form-item>
		</el-form>

		<el-table
			ref="multipleTableRef"
			v-loading="state.dataListLoading"
			:data="dataList"
			stripe
			border
			element-loading-background="rgba(0, 0, 0, 0.5)"
			element-loading-text="加载中..."
			header-row-class-name="table-header"
		>
			<!-- :selectable="checkSelectable" -->
			<el-table-column type="selection" header-align="center" align="center" width="55" fixed="left" />
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60" fixed="left"></el-table-column>
			<el-table-column label="项目名称" align="center" prop="researchName" width="200" show-overflow-tooltip fixed="left" resizable sortable />
			<el-table-column label="联系人" align="center" prop="contacts" resizable sortable> </el-table-column>
			<el-table-column label="联系电话" align="center" prop="contactsTel" width="150" resizable sortable> </el-table-column>
			<el-table-column label="负责人" align="center" prop="principal" resizable sortable> </el-table-column>
			<el-table-column label="负责人电话" align="center" prop="principalTel" width="150" resizable sortable> </el-table-column>
			<el-table-column label="承担单位" align="center" prop="responsibleEnt" width="200" show-overflow-tooltip resizable sortable> </el-table-column>
			<el-table-column label="课题总经费(万元)" align="center" prop="projectFunding" width="150" resizable sortable> </el-table-column>
			<el-table-column label="申报年份" align="center" prop="applyYear" resizable sortable> </el-table-column>
			<el-table-column label="项目管理员" align="center" prop="projectManager" width="160" resizable sortable> </el-table-column>
			<el-table-column label="申报阶段" align="center" resizable sortable>
				<template #default="scope">
					{{ getProgressStateName(scope.row.processStage) }}
				</template>
			</el-table-column>
			<el-table-column label="申报状态" align="center">
				<template #default="scope">
					{{ scope.row.processStatus === '0' ? '未提交' : '提交' }}
				</template>
			</el-table-column>

			<el-table-column label="预审" align="center" width="200" resizable sortable>
				<template #default="scope">
					<el-radio-group
						v-if="scope.row.processStage > '1' && scope.row.auditResultPre != null"
						v-model="scope.row.auditResultPre"
						:disabled="scope.row.processStage > '1'"
					>
						<el-radio v-for="data in radioList" :key="data.value" :value="data.value">{{ data.name }}</el-radio>
					</el-radio-group>
					<el-radio-group
						v-if="scope.row.processStage == '1' && scope.row.permission == 1"
						v-model="scope.row.status"
						:disabled="scope.row.processStage > '1'"
					>
						<el-radio v-for="data in radioList" :key="data.value" :value="data.value">{{ data.name }}</el-radio>
					</el-radio-group>
				</template>
			</el-table-column>
			<el-table-column label="立项评审" align="center" width="200" resizable sortable>
				<template #default="scope">
					<el-radio-group
						v-if="scope.row.processStage > '2' && scope.row.auditResultRev != null"
						v-model="scope.row.auditResultRev"
						:disabled="scope.row.processStage > '2'"
					>
						<el-radio v-for="data in radioList1" :key="data.value" :value="data.value">{{ data.name }}</el-radio>
					</el-radio-group>

					<el-radio-group
						v-if="scope.row.processStage == '2' && scope.row.permission == 1"
						v-model="scope.row.status"
						:disabled="scope.row.processStage === '1'"
					>
						<el-radio v-for="data in radioList1" :key="data.value" :value="data.value">{{ data.name }}</el-radio>
					</el-radio-group>
				</template>
			</el-table-column>

			<el-table-column label="最终结论" align="center" resizable sortable>
				<template #default="scope">
					{{ scope.row.approvalReview == null ? '' : scope.row.approvalReview === '6' ? '立项' : '不立项' }}
				</template>
			</el-table-column>

			<el-table-column label="立项批文" align="center" resizable sortable>
				<template #default="scope">
					<div class="cursor" @click="handlelook(scope.row.documentRecordList[0])">
						{{
							scope.row.documentRecordList.length > 0
								? scope.row.documentRecordList[0].fileRealName + '.' + scope.row.documentRecordList[0].fileExtName
								: ''
						}}
					</div>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="110">
				<template #default="scope">
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="handview(scope.row)">
						<View />
					</el-icon>
					<el-icon
						v-if="scope.row.permission === '1' && (scope.row.processStage === '1' || scope.row.processStage === '2')"
						:size="16"
						color="#1491FF"
						title="意见及文件上传"
						style="cursor: pointer; margin: 0 6px"
						@click="handmessage(scope.row)"
						><ChatLineRound
					/></el-icon>
					<el-icon
						v-if="scope.row.processStage === '1'"
						:size="16"
						color="#1491FF"
						title="退回"
						style="cursor: pointer; margin: 0 6px"
						@click="handback(scope.row)"
					>
						<RefreshLeft
					/></el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
	</el-card>

	<cmDialog v-model="showback" modal-title="系统提示" width="600px">
		<div style="font-size: 16px; margin-bottom: 20px; text-align: center">是否确认退回修改？</div>
		<el-form ref="backFormRef" :model="backForm" :rules="backRules" label-width="130px">
			<el-form-item label="退回原因" prop="remark">
				<el-input v-model="backForm.remark"> </el-input>
			</el-form-item>
		</el-form>
		<div class="dialog-foot">
			<el-button @click="showback = false">取消</el-button>
			<el-button type="primary" @click="submitbackForm(backFormRef)">确认</el-button>
		</div>
	</cmDialog>

	<!-- 单个文件上传 -->
	<cmDialog v-model="showmessage" modal-title="意件及文件上传" width="600px">
		<el-form ref="messageFormRef" :model="messageForm" :rules="messageRules" label-width="130px">
			<el-form-item label="意见附件类型">
				<el-radio-group v-model="messageForm.stage">
					<!-- :disabled="!messageisedit" -->
					<el-radio v-for="item in nodeList" :key="item.value" :value="item.value">{{ item.name }}</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="附件(pdf)" prop="filesRecordList">
				<el-upload
					style="width: 90%"
					:action="uploadApi"
					:headers="uploadHeaders"
					:data="Number(messageForm.stage) === 1 ? uploadData : uploadData2"
					accept=".pdf"
					:on-success="handleUploadSuccess"
					:on-exceed="handleExceed"
					:file-list="uploadList"
					:on-preview="handleUploadPdfPreview"
					:on-error="handleUploadError"
					:on-remove="handleUploadPdfRemove"
				>
					<el-button>上传文件</el-button>
				</el-upload>
			</el-form-item>

			<el-form-item v-if="messageForm.stage === '2'" label="批文年度" prop="approvalFileYear">
				<el-date-picker
					v-model="messageForm.approvalFileYear"
					type="year"
					placeholder="选择年份"
					format="YYYY"
					value-format="YYYY"
					style="width: 220px"
				/>
			</el-form-item>
			<el-form-item v-if="messageForm.stage === '2'" label="批文号" prop="approvalFileNumber">
				<el-input-number :controls="false" v-model="messageForm.approvalFileNumber" placeholder="批文号" style="width: 220px;" />
			</el-form-item>
			<el-form-item label="意见" prop="opinions">
				<el-input v-model="messageForm.opinions" type="textarea" :rows="4" placeholder="请输入内容" maxlength="300" />
			</el-form-item>
		</el-form>
		<div class="dialog-foot">
			<el-button @click="showmessage = false">取消</el-button>
			<el-button type="primary" @click="submitmessageForm()">确认</el-button>
		</div>
	</cmDialog>

	<!-- 批量 -->
	<cmDialog v-model="showfile" modal-title="文件上传" width="50%">
		<el-form ref="fileFormRef" :model="fileForm" :rules="fileRules" label-width="150px">
			<!-- <el-form-item label="意见附件类型">
				<div>{{ fileForm.processStage == 1 ? '预审' : '立项评审' }} :disabled="!fileisedit</div>
			</el-form-item> -->
			<el-form-item label="意见附件类型">
				<el-radio-group v-model="fileForm.processStage">
					<el-radio v-for="item in nodeList" :key="item.value" :value="item.value">{{ item.name }}</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item v-if="fileForm.processStage === '1'" label="评审意见附件(pdf):" prop="filesRecordList1">
				<el-upload
					:action="uploadApi"
					:headers="uploadHeaders"
					:data="uploadData"
					accept=".pdf"
					style="width: 90%"
					:on-success="handleUploadSuccess1"
					:on-exceed="handleExceed"
					:file-list="uploadList1"
					:on-preview="handleUploadPdfPreview"
					:on-error="handleUploadError1"
					:on-remove="handleUploadPdfRemove1"
				>
					<el-button>上传文件</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item v-if="fileForm.processStage === '2'" label="立项批文附件(pdf)" prop="filesRecordList2">
				<el-upload
					:action="uploadApi"
					:headers="uploadHeaders"
					:data="uploadData2"
					accept=".pdf"
					style="width: 90%"
					:on-success="handleUploadSuccess2"
					:on-exceed="handleExceed"
					:file-list="uploadList2"
					:on-preview="handleUploadPdfPreview"
					:on-error="handleUploadError2"
					:on-remove="handleUploadPdfRemove2"
				>
					<!--				:before-upload="beforeUploadPdf" :before-upload="beforeUploadPdf" -->
					<el-button>上传文件</el-button>
				</el-upload>
			</el-form-item>

			<el-form-item v-if="fileForm.processStage === '2'" label="批文年度" prop="approvalFileYear">
				<el-date-picker
					v-model="fileForm.approvalFileYear"
					type="year"
					placeholder="选择年份"
					format="YYYY"
					value-format="YYYY"
					style="width: 220px"
				/>
			</el-form-item>
			<el-form-item v-if="fileForm.processStage === '2'" label="批文号" prop="approvalFileNumber">
				<el-input-number :controls="false" v-model="fileForm.approvalFileNumber" placeholder="批文号" style="width: 220px" />
			</el-form-item>
		</el-form>
		<div class="dialog-foot">
			<el-button @click="showfile = false">取消</el-button>
			<el-button type="primary" @click="submitfileForm()">提交</el-button>
			<el-button type="success" @click="exportToExcel">导出</el-button>
		</div>

		<div></div>
		<el-table :data="checkList" class="mt20" stripe element-loading-background="rgba(0, 0, 0, 0.5)" element-loading-text="加载中...">
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
			<el-table-column label="项目名称" align="center" prop="researchName" width="200" />

			<el-table-column label="承担单位" align="center" prop="responsibleEnt"> </el-table-column>
			<el-table-column label="申请经费(万元)" align="center" prop="projectFunding"> </el-table-column>
			<el-table-column label="申报年份" align="center" prop="applyYear"> </el-table-column>
			<el-table-column label="申报阶段" align="center">
				<template #default="scope">
					{{ getProgressStateName(scope.row.processStage) }}
				</template>
			</el-table-column>
			<el-table-column label="预审" align="center" width="120">
				<template #default="scope">
					{{ scope.row.auditResultPre ? (scope.row.auditResultPre === '4' ? '拟立项' : '拟不立项') : '未评审' }}
				</template>
			</el-table-column>
			<el-table-column label="立项评审" align="center" width="120">
				<template #default="scope">
					{{ scope.row.auditResultRev ? (scope.row.auditResultRev == '6' ? '立项' : '不立项') : '未评审' }}
				</template>
			</el-table-column>
		</el-table>
	</cmDialog>

	<!--重新上传  -->
	<cmDialog v-model="showfile1" modal-title="文件上传" width="50%">
		<el-form ref="fileFormRef1" :model="fileForm1" :rules="fileRules1" label-width="150px">
			<el-form-item label="立项批文附件(pdf)" prop="filesRecordList2">
				<el-upload
					:action="uploadApi"
					:headers="uploadHeaders"
					:data="uploadData2"
					accept=".pdf"
					style="width: 90%"
					:on-success="handleUploadSuccess4"
					:on-exceed="handleExceed"
					:file-list="uploadList4"
					:on-preview="handleUploadPdfPreview"
					:on-error="handleUploadError4"
					:on-remove="handleUploadPdfRemove4"
				>
					<!--				:before-upload="beforeUploadPdf" :before-upload="beforeUploadPdf" -->
					<el-button>上传文件</el-button>
				</el-upload>
			</el-form-item>

			<el-form-item label="批文年度">
				<el-date-picker
					v-model="fileForm1.approvalFileYear"
					type="year"
					placeholder="选择年份"
					format="YYYY"
					value-format="YYYY"
					style="width: 220px"
				/>
			</el-form-item>
			<el-form-item label="批文号">
				<el-input-number :controls="false" v-model="fileForm1.approvalFileNumber" placeholder="批文号" style="width: 220px" />
			</el-form-item>
		</el-form>
		<div class="dialog-foot">
			<el-button @click="showfile1 = false">取消</el-button>
			<el-button type="primary" @click="submitfileForm1()">发布</el-button>
		</div>

		<el-table :data="checkList" class="mt20" stripe element-loading-background="rgba(0, 0, 0, 0.5)" element-loading-text="加载中...">
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
			<el-table-column label="项目名称" align="center" prop="researchName" width="200" />

			<el-table-column label="承担单位" align="center" prop="responsibleEnt"> </el-table-column>
			<el-table-column label="申请经费(万元)" align="center" prop="projectFunding"> </el-table-column>
			<el-table-column label="申报年份" align="center" prop="applyYear"> </el-table-column>
			<el-table-column label="申报阶段" align="center">
				<template #default="scope">
					{{ getProgressStateName(scope.row.processStage) }}
				</template>
			</el-table-column>
			<el-table-column label="预审" align="center" width="120">
				<template #default="scope">
					{{ scope.row.auditResultPre ? (scope.row.auditResultPre === '4' ? '拟立项' : '拟不立项') : '未评审' }}
				</template>
			</el-table-column>
			<el-table-column label="立项评审" align="center" width="120">
				<template #default="scope">
					{{ scope.row.auditResultRev ? (scope.row.auditResultRev == '6' ? '立项' : '不立项') : '未评审' }}
				</template>
			</el-table-column>
		</el-table>
	</cmDialog>
	<add v-model:visible="addvisible" :sid="sid" />
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import add from './components/add.vue'

import {
	batchAuditApi,
	doPublishApi,
	doReturnApi,
	queryAuditListApi,
	queryOpinionsApi,
	queryStageApi,
	revokeApprovalApi,
	saveFilesApi,
	saveOpinionsApi
} from '@/api/Prospect-project/project-declare'
import { filePreviewById, filePreviewByName } from '@/api/sys/upload'
import cmDialog from '@/components/cm-dialog/index.vue'
import { UploadFile } from '@/interface/declare'
import { useDictionaryStore } from '@/store/modules/dictionary'
import axios from 'axios'
import type { FormInstance, TableInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'

const route = useRoute()
const pendingStatus = route.query.pendingStatus

import { useUserStore } from '@/store/modules/user'
import * as XLSX from 'xlsx'
const userStore = useUserStore()
const state = reactive({
	queryForm: {
		researchName: '',
		projectNumber: '',
		principal: '',
		contacts: '',
		processStage: '',
		processStatus: '',
		approvalReview: '',
		startYear: '',
		endYear: '',
		responsibleEnt: '',
		pendingStatus: pendingStatus || ''
	},
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false,
	keyType: '',
	keyword: null,
	yearrange: []
})
const sid = ref('')
const multipleTableRef = ref<TableInstance>()
const showback = ref(false)
const backFormRef = ref(null)
const fileFormRef = ref(null)
const fileFormRef1 = ref(null)

const showmessage = ref(false)
const showfile = ref(false)
const showfile1 = ref(false)
const messageFormRef = ref(null)
const queryForm = ref()
const datatimelist = ref([])
const loading = ref(false)
const checkList = ref([])
const dictionaryStore = useDictionaryStore()
const progressStatelist = dictionaryStore.getDictionaryByCode('T011')
const processStatuslist = dictionaryStore.getDictionaryByCode('T004')
const approvalReviewlist = dictionaryStore.getDictionaryByCode('T013')

const radioList = ref([
	{ value: '4', name: '拟立项' },
	{ value: '5', name: '拟不立项' }
])
const radioList1 = ref([
	{ value: '6', name: '立项' },
	{ value: '7', name: '不立项' }
])
const addvisible = ref(false)
const dataList = ref([])
const messageForm = reactive({
	id: '',
	opinions: '',
	stage: '1',
	filesRecordList: [],
	filesRecordList2: [],
	approvalFileYear: '',
	approvalFileNumber: ''
})
const fileForm = reactive({
	ids: [],
	processStage: '',
	approvalFileYear: '',
	approvalFileNumber: '',
	filesRecordList2: [],
	filesRecordList1: []
})
const fileForm1 = reactive({
	ids: [],
	approvalFileYear: '',
	approvalFileNumber: '',
	filesRecordList2: []
})
const messageRules = reactive<any>({
	opinions: [{ required: true, message: '请输入意见', trigger: 'blur' }],
	filesRecordList: [{ required: true, message: '请上传附件', trigger: 'change' }],
	approvalFileYear: [{ required: true, message: '请选择批文年度', trigger: 'change' }],
	approvalFileNumber: [{ required: true, message: '请输入批文号', trigger: 'blur' }]
})
const fileRules = reactive<any>({
	filesRecordList1: [{ required: true, message: '请上传附件', trigger: 'change' }],
	filesRecordList2: [{ required: true, message: '请上传附件', trigger: 'change' }],
	approvalFileYear: [{ required: true, message: '请选择批文年度', trigger: 'change' }],
	approvalFileNumber: [{ required: true, message: '请输入批文号', trigger: 'blur' }]
})

const backRules = reactive<any>({
	remark: [{ required: true, message: '请输入退回原因', trigger: 'blur' }]
})
const backForm = reactive({
	id: '',
	codeType: 'ScientificResearchApply',
	remark: ''
})

const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const uploadData = {
	extCode: 'ResearchPrereviewComments',
	remark: '预审评审意见附件'
}

const uploadData1 = {
	extCode: 'ResearchProjectReview',
	remark: '评审意见附件'
}

const uploadData2 = {
	extCode: 'ResearchProjectApprovalDocument',
	remark: '立项批文'
}

const handview = (row: any) => {
	sid.value = row.id
	addvisible.value = true
}
// 判断某一行是否允许勾选
const checkSelectable = row => {
	// 仅当 status === 1 或 status === 2 时允许勾选
	return row.processStage === '1' || row.processStage === '2'
}

const handlelook = async (file: any) => {
	if (file) {
		filePreviewById(file.id).then(res => {
			window.open(res.data.url)
		})
	}
}

// 准备导出数据(转换为中文表头)
const prepareExportData = () => {
	// 创建带中文表头的数组
	const headerRow = Object.values(tableHeaders)
	const dataRows = checkList.value.map(row => [
		row.index,
		row.researchName,
		row.responsibleEnt,
		row.projectFunding,
		row.applyYear,
		row.processStage,
		row.auditResultRev
	])

	return [headerRow, ...dataRows]
}

// 表格表头(中文)
const tableHeaders = {
	index: '序号',
	researchName: '项目名称',
	responsibleEnt: '承担单位',
	projectFunding: '申请经费(万元)',
	applyYear: '申报年份',
	processStage: '申报阶段',
	auditResultPre: '预审',
	auditResultRev: '立项评审'
}
// 导出为Excel
const exportToExcel1 = () => {
	try {
		const exportData = prepareExportData()
		const worksheet = XLSX.utils.aoa_to_sheet(exportData)
		const workbook = XLSX.utils.book_new()
		XLSX.utils.book_append_sheet(workbook, worksheet, '员工数据')

		// 导出Excel
		XLSX.writeFile(workbook, '员工数据.xlsx')
		//	showToast('Excel文件导出成功！')
	} catch (error) {
		console.error('导出Excel失败:', error)
		//	showToast('导出失败，请重试', 'error')
	}
}

const exportHandle = () => {
	try {
		switch (state.keyType) {
			case '1':
				state.queryForm.projectNumber = state.keyword
				break
			case '2':
				state.queryForm.researchName = state.keyword
				break
			case '3':
				state.queryForm.principal = state.keyword
				break
			case '4':
				state.queryForm.contacts = state.keyword
				break
			case '5':
				state.queryForm.responsibleEnt = state.keyword
				break
		}
		state.queryForm.startYear = state.yearrange[0] || ''
		state.queryForm.endYear = state.yearrange[1] || ''

		const param = {
			pageIndex: state.pageNum,
			pageSize: state.pageSize,
			...state.queryForm
		}
		axios({
			method: 'post',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/scientificResearchInfo/export',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			data: param,
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = '前瞻性项目汇总表.xls'
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const exportToExcel = () => {
	const dataRows = checkList.value.map((row, index) => {
		return {
			index: index + 1,
			researchName: row.researchName,
			responsibleEnt: row.responsibleEnt,
			projectFunding: row.projectFunding,
			applyYear: row.applyYear,
			processStage: getProgressStateName(row.processStage),
			auditResultPre: row.auditResultPre ? (row.auditResultPre == '4' ? '拟立项' : '拟不立项') : '拟立项',
			auditResultRev: row.auditResultRev ? (row.auditResultRev == '6' ? '立项' : '不立项') : '不立项'
		}
	})
	console.log(dataRows, 'sgsgsg')
	const dataWithChineseHeaders = dataRows.map(item => {
		const newItem = {}
		Object.keys(item).forEach(key => {
			newItem[tableHeaders[key]] = item[key] // 替换为中文表头
		})
		return newItem
	})

	console.log(dataWithChineseHeaders, 'sgsgsg')
	// 1. 创建工作簿
	const wb = XLSX.utils.book_new()

	// 2. 将数据转换为工作表
	//const exportData = prepareExportData()
	const ws = XLSX.utils.json_to_sheet(dataWithChineseHeaders)

	// 3. 将工作表添加到工作簿
	XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

	// 4. 导出文件
	XLSX.writeFile(wb, '数据列表.xlsx')
}
const hasPermission = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => row.permission == 1)

	// const firstApplyStage = selectedRows[0].applyStage
	// const allApplyStageSame = selectedRows.every(row => row.applyStage === firstApplyStage)

	return allPermissionValid
})
const hasPermissionfb = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}
	console.log(selectedRows, 'selectedRows')
	const allPermissionValid = selectedRows.every(row => row.publishStatus == 0)

	// const firstApplyStage = selectedRows[0].applyStage
	// const allApplyStageSame = selectedRows.every(row => row.applyStage === firstApplyStage)

	return allPermissionValid
})
const hasPermissionqxfb = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}
	console.log(selectedRows, 'selectedRows')
	const allPermissionValid = selectedRows.every(row => row.publishStatus == 1)

	// const firstApplyStage = selectedRows[0].applyStage
	// const allApplyStageSame = selectedRows.every(row => row.applyStage === firstApplyStage)

	return allPermissionValid
})
const hasPermission2 = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => row.processStage < 3 && row.processStage >= 1)

	// const firstApplyStage = selectedRows[0].applyStage
	// const allApplyStageSame = selectedRows.every(row => row.applyStage === firstApplyStage)

	return allPermissionValid
})

const hasPermission3 = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => row.documentRecordList.length > 0)

	// const firstApplyStage = selectedRows[0].applyStage
	// const allApplyStageSame = selectedRows.every(row => row.applyStage === firstApplyStage)

	return allPermissionValid
})

const reissueHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}

		showfile1.value = true
		checkList.value = selectedRows
		selectedRows.forEach(row => {
			fileForm1.ids.push(row.id)
		})

		console.log(fileForm1.ids, 'fileForm1.ids')
	} catch (error) {
		showToast(error.message, 'error')
	}
}
onMounted(() => {
	getDataList()
})
const handleDateChange = val => {
	// 清空时，val 为 null，手动设置为空字符串

	datatimelist.value = val || [] // 清空时重置为空数组
}

const statusMap = {
	'1': '未处理',
	'2': '推荐',
	'3': '不推荐',
	'4': '拟立项',
	'5': '拟不立项',
	'6': '立项',
	'7': '不立项',
	'8': '退回'
}
const submitHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}

		const firstStatus = selectedRows[0].processStage

		const status = selectedRows.every(item => item.processStage === firstStatus)
		if (selectedRows.length > 1) {
			if (!status) {
				throw new Error('请选择相同状态的项目')
			}
		}

		const unprocessedIndices = []

		selectedRows.forEach((row, index) => {
			if (!row.status) {
				if (!row.status) {
					unprocessedIndices.push(index + 1)
				}
			}
		})

		if (unprocessedIndices.length > 0) {
			throw new Error(`序号为${unprocessedIndices.join('、')}的数据未处理，请检查！`)
		}
		const tableList = []
		selectedRows.forEach(row => {
			tableList.push({
				id: row.id,
				status: row.status
			})
		})
		ElMessageBox.confirm(`是否需要上传审核意见，如果需要请先填写意见？`, '温馨提示', {
			confirmButtonText: '直接提交审核',
			cancelButtonText: '去上传审核意见',
			type: 'warning'
		})
			.then(() => {
				submit(tableList)
				// batchAuditApi({ tableList: tableList }).then(() => {
				// 	ElMessage.success('操作成功')
				// 	getDataList()
				// })
			})
			.catch(() => {})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const submit = (tableList: any) => {
	const ishas = tableList.some(item => item.status === '5')

	console.log(ishas, 'ishas')
	console.log(tableList, 'tableList')
	if (ishas) {
		ElMessageBox.confirm(`拟不立项审核结论就是不立项，项目结束,是否确认选择？`, '温馨提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				batchAuditApi({ tableList: tableList }).then(() => {
					ElMessage.success('操作成功')
					getDataList()
				})
			})
			.catch(() => {})
	} else {
		batchAuditApi({ tableList: tableList }).then(() => {
			ElMessage.success('操作成功')
			getDataList()
		})
	}
}

const fileisedit = ref(false)
const submitfileHandle = () => {
	fileForm.ids = []
	uploadList1.value = []
	uploadList2.value = []
	fileForm.filesRecordList1 = []
	fileForm.filesRecordList2 = []
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}

		const firstStatus = selectedRows[0].processStage
		const status = selectedRows.every(item => item.processStage === firstStatus)
		if (selectedRows.length > 1) {
			if (!status) {
				throw new Error('请选择相同状态的项目')
			}
		}
		checkList.value = selectedRows

		selectedRows.forEach(row => {
			fileForm.ids.push(row.id)
		})

		queryStageApi({ id: checkList.value[0].id }).then(res => {
			fileForm.processStage = res.data[0].stage.toString()
			nodeList.value = res.data[0].nodeList
			if (fileForm.processStage === res.data[0].nodeList[0].value) {
				fileisedit.value = true
			} else {
				fileisedit.value = false
			}
		})
		showfile.value = true
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const cancelApprovalFIleHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}

		const firstStatus = selectedRows[0].processStage
		const status = selectedRows.every(item => item.processStage === firstStatus)
		if (selectedRows.length > 1) {
			if (!status) {
				throw new Error('请选择相同状态的项目')
			}
		}

		const ids = []
		selectedRows.forEach(row => {
			ids.push(row.id)
		})

		ElMessageBox.confirm(`是否确认取消发布？`, '温馨提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				revokeApprovalApi({ ids: ids }).then(res => {
					ElMessage.success('取消发布成功')
					getDataList()
				})
			})
			.catch(() => {})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const handleExceed: UploadProps['onExceed'] = files => {
	ElMessageBox.confirm('只能上传一份文件，若要替换，请先删除已有文件', '温馨提示', {
		showConfirmButton: false,
		cancelButtonText: '知道了',
		type: 'warning'
	})
}

const handleUploadPdfPreview = (ruploadFile: any) => {
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}

const handleUploadPdfRemove = (file: UploadRawFile) => {
	uploadList.value = []
	messageForm.filesRecordList = []
}

const handleUploadPdfRemove1 = (file: UploadRawFile) => {
	uploadList1.value = []
	fileForm.filesRecordList1 = []
}
const handleUploadPdfRemove2 = (file: UploadRawFile) => {
	uploadList2.value = []
	fileForm.filesRecordList2 = []
}
const handleUploadError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadList.value = uploadList.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	messageForm.filesRecordList = uploadList.value
}
const uploadList = ref<UploadFile[]>([])
const handleUploadSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadList.value.push(res.data)
		messageForm.filesRecordList = uploadList.value
	} else {
		handleUploadError(res, uploadFile)
	}
}

const uploadList1 = ref<UploadFile[]>([])
const handleUploadSuccess1 = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadList1.value.push(res.data)
		fileForm.filesRecordList1 = uploadList1.value
	} else {
		handleUploadError1(res, uploadFile)
	}
}
const handleUploadError1 = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadList1.value = uploadList1.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	fileForm.filesRecordList1 = uploadList1.value
}
const uploadList2 = ref<UploadFile[]>([])
const handleUploadSuccess2 = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadList2.value.push(res.data)
		fileForm.filesRecordList2 = uploadList2.value
	} else {
		handleUploadError2(res, uploadFile)
	}
}

const handleUploadError2 = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadList2.value = uploadList2.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	fileForm.filesRecordList2 = uploadList2.value
}

const uploadList4 = ref<UploadFile[]>([])
const handleUploadSuccess4 = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadList4.value.push(res.data)
		fileForm1.filesRecordList2 = uploadList2.value
	} else {
		handleUploadError2(res, uploadFile)
	}
}
const handleUploadPdfRemove4 = (file: UploadRawFile) => {
	uploadList4.value = []
	fileForm1.filesRecordList2 = []
}
const handleUploadError4 = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadList4.value = uploadList4.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	fileForm1.filesRecordList2 = uploadList4.value
}

const handleUploadPdfRemove3 = (file: UploadRawFile) => {
	uploadList3.value = []
	messageForm.filesRecordList2 = []
}
const uploadList3 = ref<UploadFile[]>([])
const handleUploadSuccess3 = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadList3.value.push(res.data)
		messageForm.filesRecordList2 = uploadList3.value
	} else {
		handleUploadError3(res, uploadFile)
	}
}

const handleUploadError3 = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadList3.value = uploadList3.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	messageForm.filesRecordList2 = uploadList3.value
}
const getProgressStateName = (row: any) => {
	switch (row) {
		case '0':
			return '申报中'
		case '1':
			return '预审'
		case '2':
			return '立项评审'
		case '3':
			return '开题'
		case '4':
			return '中期'
		case '5':
			return '结题'
		case '6':
			return '等待归档'
		case '7':
			return '归档'
	}
}

const getProgressStateName1 = (row: any) => {
	switch (row) {
		case '4':
			return '拟立项'
		case '5':
			return '拟不立项'
	}
}

const getProgressStateName2 = (row: any) => {
	switch (row) {
		case '6':
			return '立项'
		case '7':
			return '不立项'
	}
}
const nodeList = ref([])
const messageisedit = ref(false)
const handmessage = (row: any) => {
	messageForm.id = ''
	messageForm.opinions = ''
	messageForm.stage = '1'
	messageForm.filesRecordList = []
	messageForm.filesRecordList2 = []
	messageForm.approvalFileNumber = ''
	messageForm.approvalFileYear = ''
	uploadList.value = []
	uploadList3.value = []
	showmessage.value = true
	messageForm.id = row.id
	queryStageApi({ id: row.id }).then(res => {
		messageForm.stage = res.data[0].stage.toString()

		nodeList.value = res.data[0].nodeList
		if (messageForm.stage === res.data[0].nodeList[0].value) {
			messageisedit.value = true
		} else {
			messageisedit.value = false
		}
	})

	queryOpinionsApi({ id: row.id, stage: row.processStage }).then(res => {
		messageForm.opinions = res.data.opinions

		messageForm.filesRecordList = res.data.filesRecordList
		messageForm.approvalFileNumber = res.data.approvalFileNumber ? res.data.approvalFileNumber.toString() : ''
		messageForm.approvalFileYear = res.data.approvalFileYear ? res.data.approvalFileYear.toString() : ''
		uploadList.value = []
		uploadList.value = res.data.filesRecordList.map((item: any) => {
			return {
				extCode: item.extCode,
				fileExtName: item.fileExtName,
				filePath: item.filePath,
				fileRealName: item.fileRealName,
				fileSize: item.fileSize,
				id: item.id,
				remark: item.remark,
				systemFileName: item.systemFileName,
				name: item.fileRealName
			}
		})
	})
}
const handback = (row: any) => {
	showback.value = true
	backForm.id = row.id
}
const submitbackForm = async (formRef: FormInstance) => {
	if (!formRef) {
		return
	}
	await backFormRef.value.validate((valid, fields) => {
		if (valid) {
			doReturnApi(backForm).then(res => {
				ElMessage({
					type: 'success',
					message: '提交成功'
				})
				showback.value = false
				getDataList()
			})
		} else {
			if (!fields) {
				return
			}
		}
	})
}

const submitmessageForm = () => {
	messageFormRef.value.validate((valid, fields) => {
		if (valid) {
			console.log(uploadList.value, 'sgsgsgsgsgg')
			const shuzu = uploadList.value.map((item: any) => {
				return {
					extCode: item.extCode,
					fileExtName: item.fileExtName,
					filePath: item.filePath,
					fileRealName: item.fileRealName,
					fileSize: item.fileSize,
					id: item.id,
					remark: item.remark,
					systemFileName: item.systemFileName
				}
			})

			const data = {
				id: messageForm.id,
				opinions: messageForm.opinions,
				stage: messageForm.stage,
				filesRecordList: shuzu,
				approvalFileYear: messageForm.approvalFileYear,
				approvalFileNumber: messageForm.approvalFileNumber
			}

			saveOpinionsApi(data).then(res => {
				ElMessage({
					type: 'success',
					message: '提交成功'
				})
				showmessage.value = false
				uploadList.value = []
				uploadList3.value = []
				messageForm.id = ''
				messageForm.opinions = ''
				messageForm.stage = '1'
				messageForm.filesRecordList = []
				messageForm.filesRecordList2 = []
				messageForm.approvalFileNumber = ''
				messageForm.approvalFileYear = ''

				getDataList()
			})
		} else {
			if (!fields) {
				return
			}
		}
	})
}

const submitfileForm = () => {
	fileFormRef.value.validate((valid, fields) => {
		if (valid) {
			const data = {
				approvalFileYear: fileForm.approvalFileYear,
				approvalFileNumber: fileForm.approvalFileNumber,
				ids: fileForm.ids,
				filesRecordList: fileForm.processStage === '1' ? uploadList1.value : uploadList2.value
			}
			saveFilesApi(data).then(res => {
				ElMessage({
					type: 'success',
					message: '提交成功'
				})
				fileForm.ids = []
				uploadList1.value = []
				uploadList2.value = []
				fileForm.filesRecordList1 = []
				fileForm.filesRecordList2 = []
				fileForm.approvalFileYear = ''
				fileForm.approvalFileNumber = ''
				checkList.value = []
				showfile.value = false
				getDataList()
			})
		} else {
			if (!fields) {
				return
			}
		}
	})
}

const submitfileForm1 = () => {
	fileFormRef1.value.validate((valid, fields) => {
		if (valid) {
			const data = {
				ids: fileForm1.ids,
				filesRecordList: uploadList4.value,
				approvalFileYear: fileForm1.approvalFileYear,
				approvalFileNumber: fileForm1.approvalFileNumber
			}
			doPublishApi(data).then(res => {
				ElMessage({
					type: 'success',
					message: '提交成功'
				})
				fileForm1.ids = []
				uploadList4.value = []
				fileForm1.filesRecordList2 = []
				fileForm1.approvalFileYear = ''
				fileForm1.approvalFileNumber = ''
				checkList.value = []
				showfile1.value = false
				getDataList()
			})
		} else {
			if (!fields) {
				return
			}
		}
	})
}
const handleSearch = () => {
	getDataList()
}
const getDataList = () => {
	switch (state.keyType) {
		case '1':
			state.queryForm.projectNumber = state.keyword
			break
		case '2':
			state.queryForm.researchName = state.keyword
			break
		case '3':
			state.queryForm.principal = state.keyword
			break
		case '4':
			state.queryForm.contacts = state.keyword
			break
		case '5':
			state.queryForm.responsibleEnt = state.keyword
			break
	}
	state.queryForm.startYear = state.yearrange[0] || ''
	state.queryForm.endYear = state.yearrange[1] || ''
	state.dataListLoading = true
	queryAuditListApi({
		pageIndex: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		state.dataListLoading = false
		dataList.value = res.data.list || []
		state.total = res.data.total || 0
	})
}
const search = () => {
	state.pageNum = 1
	getDataList()
}

// const godetail = () => {
// 	router.push({
// 		path: '/bzjddetail'
// 	})
// }

const reset = () => {
	state.queryForm.startYear = ''
	state.queryForm.endYear = ''
	state.queryForm.researchName = ''
	state.queryForm.projectNumber = ''
	state.queryForm.principal = ''
	state.queryForm.contacts = ''
	state.queryForm.processStage = ''
	state.queryForm.processStatus = ''
	state.queryForm.approvalReview = ''
	state.queryForm.responsibleEnt = ''
	state.queryForm.pendingStatus = ''
	state.keyword = null
	state.keyType = ''
	state.pageNum = 1
	datatimelist.value = []
	getDataList()
}

const sizeChangeHandle = (e: number) => {
	state.pageSize = e
	state.pageNum = 1
	getDataList()
}
const currentChangeHandle = (e: number) => {
	state.pageNum = e
	getDataList()
}
</script>

<style lang="scss" scoped>
.dialog-foot {
	display: flex;
	justify-content: center;
	padding-top: 20px;
	margin-bottom: 10px;
}

.el-form--inline .el-form-item {
	margin-right: 10px !important;
}

::v-deep(.el-input-number .el-input__inner) {
	text-align: left;
}
</style>
